﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EZ_B;
using System.Collections;

namespace GeneralAdaptiveFramework
{
    public delegate void UpdateSensor(CollectInfo collectInfo);
    public class Collect : PassiveComponent
    {
        public CollectInfo collectInfo = new CollectInfo();
        public static CollectForm collectForm = new CollectForm();

        //System.IO.StreamWriter file = new System.IO.StreamWriter("objLocation.txt");

        public Collect(string _name)
            : base(_name)
        {
            initPort();
        }

        /**
         * Init two Provide ports and two Require ports
         */
        private void initPort()
        {
            interfaceList = new ArrayList();

            ProvideInterface provider01 = new ProvideInterface("PCollect01", this);
            ProvideInterface provider02 = new ProvideInterface("PCollect02", this);
            RequireInterface require01 = new RequireInterface("RCollect01", this);
            RequireInterface require02 = new RequireInterface("RCollect02", this);

            interfaceList.Add(provider01);
            interfaceList.Add(provider02);
            interfaceList.Add(require01);
            interfaceList.Add(require02);
        }

        /**
         * Show the collect form
         */
        public void showForm()
        {
            collectForm.connect();
            collectForm.updateSensor += new UpdateSensor(this.execute);
            collectForm.Visible = true;
        }

        /**
         * Receive data
         */
        public override void receiveData(Object data)
        {
            // add data to buffer
            buffer.Add(data);

            // call execute
            execute();
        }

        public void execute(CollectInfo collectInfo)
        {
#if DEBUG
            Console.WriteLine("Collect: " + collectInfo.objectLocation.centerX);
#endif
            transferData(collectInfo);
        }

        /**
         * Collect the object location by ColorDetection
         */
        public override void execute()
        {
            // get data from buffer
            // the data is a string command
            if (buffer.Count > 0)
            {
                string command = (string)buffer[0];
                buffer.RemoveAt(0);
#if DEBUG
                Console.WriteLine("COLLECT receives {0}", command);
#endif
                switch (command)
                {
                    case "STOP":
                        collectForm.disconnect();
                        collectForm.Visible = false;
                        break;
                    case "EXECUTE":
                        showForm();
                        break;
                }
            }
        }
    }
}
